package com.outsourcing.bottle;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.PendingIntent;
import android.app.PendingIntent.CanceledException;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.support.v4.app.FragmentActivity;
import android.telephony.TelephonyManager;
import android.util.DisplayMetrics;
import android.view.ContextThemeWrapper;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.Toast;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.outsourcing.bottle.ui.HomeActivity;
import com.outsourcing.bottle.ui.LoginPlatformActivity;
import com.outsourcing.bottle.util.ActivityManager;
import com.outsourcing.bottle.util.AppContext;
import com.outsourcing.bottle.util.BasicUIEvent;
import com.outsourcing.bottle.util.BottleApplication;
import com.outsourcing.bottle.util.CommandTaskEvent;
import com.outsourcing.bottle.util.TextUtil;
import com.outsourcing.bottle.widget.CustomDialog;

/**
 * 
 * @author mzba
 * 
 */
public class BasicActivity extends FragmentActivity implements BasicUIEvent {

	public static final int DESTROYDIALOG = 0x00000101;
	private final static int cancelAlertDialog = 0x00000102;
	private final static int destroyDialogByFinish = 0x00000103;
	public CustomDialog dialog;
	protected Toast toast;
	public int CanvasHeight;
	public int CanvasWidth;
	
	public BottleApplication app;
	
	private double latitude; 
	private double longitude; 
	
	public String bestProvider;
	public LocationManager locationManager;
	public Location location;
	public static final int open_location_network = 2001;

	public LocationClient mLocationClient = null;
	public MyLocationListenner myListener = new MyLocationListenner();
	public String countryIso;

	@Override
	protected void onCreate(Bundle paramBundle) {
		super.onCreate(paramBundle);
		AppContext.setContext(this);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		TextUtil.setCtxForGetResString(this);
		ActivityManager.addActivity(this);
		LinearLayout layout = new LinearLayout(this);
		Button bt = new Button(this);
		layout.addView(bt);
		DisplayMetrics displayMetrics = new DisplayMetrics();
		this.getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
		CanvasWidth = displayMetrics.widthPixels;
		CanvasHeight = displayMetrics.heightPixels;
//		getWindow().setSoftInputMode(
//				WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
		
		locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
		if (bestProvider == null) {
			bestProvider = locationManager.getBestProvider(getCriteria(), false);
			if (bestProvider == null) {
				bestProvider = LocationManager.NETWORK_PROVIDER;
			}
		}
		location = locationManager.getLastKnownLocation(bestProvider);
	}

	@Override
	protected void onResume() {
		super.onResume();
		if (AppContext.getContext() instanceof SplashActivity
				|| AppContext.getContext() instanceof LoginPlatformActivity) {
			return;
		}
		if (AppContext.getInstance().getLogin_uid() == 0
				|| AppContext.getInstance().getLogin_token() == null) {
			initConfig();
		}
	}
	
	@Override
	public boolean onKeyUp(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_HOME) {
			Intent intent;
			if (AppContext.getContext() == null) {
				intent = new Intent(this, HomeActivity.class);
			} 
			else {
				intent = new Intent(this, AppContext.getContext().getClass());
			}
			intent.setAction("android.intent.action.MAIN");
			intent.addCategory("android.intent.category.LAUNCHER");
			intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			intent.addFlags(Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
		}
		return super.onKeyUp(keyCode, event);
	}
	
	@Override
	protected void onDestroy() {
		if (toast != null) {
			toast.cancel();
		}
		super.onDestroy();
	}

	protected boolean onBackClick() {
		finish();
		return false;
	}

	public View getLayoutView(int layout) {
		return LayoutInflater.from(this).inflate(layout, null);
	}

	@Override
	public void execute(int mes, Object obj) {

	}

	public void eventTask(int CommandID, String tips, Object obj) {
		try {
			CommandTaskEvent com = new CommandTaskEvent(this, this, tips);
			com.execute((new Object[] { CommandID + "", obj }));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public AlertDialog alert = null;
	public boolean alertIsShow = false;

	public void loading(String msg) {
		try {
			if (this.isFinishing()) {
				return;
			}
			if (dialog == null || !dialog.isShowing()) {
				View progressview = LayoutInflater.from(BasicActivity.this)
						.inflate(R.layout.progress_dialog, null);
				CustomDialog.Builder progressBuilder = new CustomDialog.Builder(
						BasicActivity.this);
				progressBuilder.setContentView(progressview);
				dialog = progressBuilder.create();
				dialog.show();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void destroyDialog() {
		basicHandler.sendEmptyMessage(DESTROYDIALOG);
	}

	public void onToast(String msg) {
		Toast.makeText(this, msg, Toast.LENGTH_LONG).show();
	}

	/**
	 * 系统信息 必须在handler或者控件触发 调用才有效
	 * 
	 * @param message
	 */
	@SuppressWarnings("deprecation")
	public void setSysMes(String message) {
		if (dialog != null && dialog.isShowing()) {
			dialog.cancel();
		}
		if (alert == null)
			alert = new AlertDialog.Builder(this).create();

		if (!alert.isShowing()) {
			alertIsShow = true;
			alert.setTitle(getString(R.string.system_info));
			alert.setMessage(message);
			alert.setButton(getString(R.string.confirm_ok),
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog,
								int whichButton) {
							alertIsShow = false;
						}
					});
			alert.setOnCancelListener(new DialogInterface.OnCancelListener() {
				public void onCancel(DialogInterface dialog) {
					alertIsShow = false;
				}
			});
			alert.show();

		}
	}

	/**
	 * 系统信息 必须在handler或者控件触发 调用才有效
	 * 
	 * @param message
	 */
	@SuppressWarnings("deprecation")
	public void setSysMes(String message, final int what) {
		if (message == null || "出错了".equals(message)) {
			return;
		}
		if (dialog != null && dialog.isShowing()) {
			dialog.cancel();
		}
		if (alert == null)
			alert = new AlertDialog.Builder(this).create();

		if (!alertIsShow) {
			alertIsShow = true;
			alert.setTitle(getString(R.string.system_info));
			alert.setMessage(message);
			alert.setButton(getString(R.string.confirm_ok),
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog,
								int whichButton) {
							sysMesPositiveButtonEvent(what);
							alertIsShow = false;
						}
					});
			alert.setOnCancelListener(new DialogInterface.OnCancelListener() {
				public void onCancel(DialogInterface dialog) {
					alertIsShow = false;
				}
			});
			alert.show();
		}
	}

	/**
	 * dismiss alert 系统信息提示框
	 */
	public void cancelAlertDialog() {
		if (alert != null && alert.isShowing()) {
			Message localMessage = Message.obtain(basicHandler, cancelAlertDialog);
			basicHandler.sendMessage(localMessage);
		}
	}

	/**
	 * 系统信息选择提示 必须在handler或者控件触发 调用才有效
	 * 
	 * @param message
	 * @param what
	 */
	public void showChoseMes(String message, final int what) {
		if (dialog != null && dialog.isShowing()) {
			dialog.cancel();
		}
		Builder alert = new AlertDialog.Builder(this); // 为了避免 setSysMes（String
														// message,final int
														// what） 出现 “否”选择
		if (!alertIsShow) {
			alertIsShow = true;
			alert.setTitle(getString(R.string.system_info));
			alert.setMessage(message);
			alert.setPositiveButton(getString(R.string.confirm_yes),
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog,
								int whichButton) {
							sysMesPositiveButtonEvent(what);
							alertIsShow = false;
						}
					});
			alert.setNegativeButton(getString(R.string.confirm_no),
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog,
								int whichButton) {
							sysMesNegativeButtonEvent(what);
							alertIsShow = false;
						}
					});
			alert.setOnCancelListener(new DialogInterface.OnCancelListener() {
				public void onCancel(DialogInterface dialog) {
					sysMesOnCancelEvent(what);
					alertIsShow = false;
				}
			});
			alert.show();
		}
	}

	/**
	 * 系统信息提示ok按钮回调方法 是 showChoseMes(String message,final int
	 * what)，setSysMes(String message,final int what)方法回调
	 */
	public void sysMesPositiveButtonEvent(int what) {

	}

	/**
	 * 系统信息提示no按钮回调方法 是 showChoseMes(String message,final int what)方法回调
	 * 
	 * @param what
	 */
	public void sysMesNegativeButtonEvent(int what) {

	}

	/**
	 * 系统信息提示no按钮回调方法 是 showChoseMes(String message,final int what)方法回调
	 * 
	 * @param what
	 */
	public void sysMesOnCancelEvent(int what) {

	}

	public void destroyDialogByFinish() {
		Message localMessage = Message.obtain(basicHandler, destroyDialogByFinish);
		basicHandler.sendMessage(localMessage);
	}

	public void finish() {
		try {
			if (dialog != null && dialog.isShowing()) {
				destroyDialogByFinish();
			} else {
				super.finish();
			}
//			ActivityManager.removeActivity(this);
			System.gc();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void finishAll() {
		try {
			if (dialog != null && dialog.isShowing()) {
				destroyDialogByFinish();
			} else {
				super.finish();
			}
			System.gc();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 选择菜单 弹出框
	 * @param choices 显示的菜单
	 * @param chooseType 菜单的类型，为了区别其他菜单
	 */
	public void chooseAction(String[] choices, final int chooseType) {
		final Context dialogContext = new ContextThemeWrapper(this, android.R.style.Theme_Light);
	
		final ListAdapter adapter = new ArrayAdapter<String>(dialogContext,
				android.R.layout.simple_list_item_1, choices);

		final AlertDialog.Builder builder = new AlertDialog.Builder(
				dialogContext);
		builder.setTitle(R.string.system_info);
		builder.setSingleChoiceItems(adapter, -1,
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
						doSelectChooseEvent(which, chooseType);
					}
				});
		builder.create().show();
	}
	
	public void doSelectChooseEvent(int which, int chooseType) {
		
	}

	public Handler basicHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case DESTROYDIALOG:
				if (dialog != null && dialog.isShowing()) {
					dialog.cancel();
				}
				break;
			case cancelAlertDialog:
				if (alert != null && alert.isShowing()) {
					alert.cancel();
				}
				break;
			case destroyDialogByFinish:
				if (dialog != null && dialog.isShowing()) {
					dialog.cancel();
				}
				BasicActivity.this.finish();
				break;
			case AppContext.GPS_LOCATE_TIMEOUT:
				System.out.println(">>>>>>>>>>>>>>>>>>>>> GPS locate timeout .............");
				networkLocat();
//				locationManager.removeUpdates(locationListener);
				break;
			case AppContext.START_GPS_LOCATE:
				if (!getGpsState(BasicActivity.this)) {
					toggleGPS();
				}
				break;
			case AppContext.GPS_LOCATE_SUCCESS:
				locateSuccess();
				break;
			case AppContext.NETWORK_LOCATE_SUCCESS:
				locateSuccess();
				break;
			default:
				break;
			}
		}
	};
	
	public void locateSuccess() {
		try {
			if (mLocationClient != null) {
				mLocationClient.stop();
			} else {
				toggleGPS();
				locationManager.removeUpdates(locationListener);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public boolean getGpsState(Context context) {
		if (null == context)
			return false;
		LocationManager alm = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
		return alm.isProviderEnabled(LocationManager.GPS_PROVIDER);

	}

	public void toggleGPS() {
		Intent gpsIntent = new Intent();
		gpsIntent.setClassName("com.android.settings", "com.android.settings.widget.SettingsAppWidgetProvider");
		gpsIntent.addCategory("android.intent.category.ALTERNATIVE");
		gpsIntent.setData(Uri.parse("custom:3"));
		try {
			PendingIntent.getBroadcast(this, 0, gpsIntent, 0).send();
		} catch (CanceledException e) {
			e.printStackTrace();
		}
	}
	
	public void initConfig() {
    	String country = getResources().getConfiguration().locale.getCountry();
		if (country.equals("CN")) {
			AppContext.setLanguage(1);
		} else {
			AppContext.setLanguage(0);
		}
    	
    	SharedPreferences preferences = getSharedPreferences("Preferences_userinfo", Activity.MODE_APPEND);
    	int login_uid = preferences.getInt("login_uid", 0);
    	String login_token = preferences.getString("login_token", null);
    	AppContext.getInstance().setLogin_uid(login_uid);
		AppContext.getInstance().setLogin_token(login_token);
    }
	
	private Criteria getCriteria() {
		Criteria criteria = new Criteria();
		criteria.setAccuracy(Criteria.ACCURACY_COARSE);
		criteria.setAltitudeRequired(false);
		criteria.setBearingRequired(false);
		criteria.setCostAllowed(true);
		criteria.setPowerRequirement(Criteria.POWER_LOW);
		return criteria;
	}
	
	public LocationListener locationListener = new LocationListener() {
		
		@Override
		public void onStatusChanged(String provider, int status, Bundle extras) {
			
		}
		
		@Override
		public void onProviderEnabled(String provider) {
			
		}
		
		@Override
		public void onProviderDisabled(String provider) {
		}
		
		@Override
		public void onLocationChanged(Location location) {
			if (location != null) {
				latitude = location.getLatitude(); 
				longitude = location.getLongitude();
				AppContext.getInstance().setLatitude(latitude);
				AppContext.getInstance().setLongitude(longitude);
				basicHandler.sendEmptyMessage(AppContext.NETWORK_LOCATE_SUCCESS);
			}
			System.out.println("-----------------------------network locate: latitude:" + latitude + ";longitude:" + longitude);
		}
	};


	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == open_location_network) {
			networkLocat();
		}
	}
	
	@SuppressWarnings("deprecation")
	public void networkLocat() {
		TelephonyManager tm = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
		countryIso = tm.getNetworkCountryIso();
		System.out.println("---------------- Country ISO ----------->>>>>>>>>>>" + countryIso);
		if (countryIso != null && countryIso.equalsIgnoreCase("cn")) {
			mLocationClient = new LocationClient( this );
			mLocationClient.registerLocationListener( myListener );
			LocationClientOption option = new LocationClientOption();
			option.setOpenGps(true);
			option.setAddrType("all");
			option.setCoorType("bd09ll");
			option.setScanSpan(0);
			option.disableCache(true);//禁止启用缓存定位
			option.setPriority(LocationClientOption.NetWorkFirst);
			mLocationClient.setLocOption(option);
			
			if (mLocationClient != null && mLocationClient.isStarted()) {
				mLocationClient.requestLocation();
			} else{
				mLocationClient.start();
				mLocationClient.requestLocation();
			}
		} else {
			if (!locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
				if (dialog != null && dialog.isShowing()) {
					dialog.cancel();
				}
				if (alert == null)
					alert = new AlertDialog.Builder(this).create();
				
				alert.setCancelable(false);
				if (!alert.isShowing()) {
					alertIsShow = true;
					alert.setTitle(getString(R.string.system_info));
					alert.setMessage(getString(R.string.locate_error_tips));
					alert.setButton(getString(R.string.confirm_ok),
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog, int whichButton) {
									alertIsShow = false;
									startActivityForResult(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS), open_location_network);
								}
							});
					alert.setOnCancelListener(new DialogInterface.OnCancelListener() {
						public void onCancel(DialogInterface dialog) {
							alertIsShow = false;
						}
					});
					alert.show();
				}
			} else {
				locationManager.requestLocationUpdates(bestProvider, 1000, 2, locationListener);
			}
		}
	}
	
	public class MyLocationListenner implements BDLocationListener {
		@Override
		public void onReceiveLocation(BDLocation location) {
			if (location == null)
				return ;
			StringBuffer sb = new StringBuffer(256);
			sb.append("time : ");
			sb.append(location.getTime());
			sb.append("\nlatitude : ");
			sb.append(location.getLatitude());
			sb.append("\nlontitude : ");
			sb.append(location.getLongitude());
			if (location.getLocType() == BDLocation.TypeGpsLocation){
			} else if (location.getLocType() == BDLocation.TypeNetWorkLocation){
				sb.append("\naddr : ");
				sb.append(location.getAddrStr());
			}
			latitude = location.getLatitude();
			longitude = location.getLongitude();
			System.out.println(sb.toString());
			AppContext.getInstance().setLatitude(latitude);
			AppContext.getInstance().setLongitude(longitude);
			basicHandler.sendEmptyMessage(AppContext.NETWORK_LOCATE_SUCCESS);
		}
		
		public void onReceivePoi(BDLocation poiLocation) {
			
		}
	}
}
